<?php
class Hit extends AppModel
{
	var $name = 'Hit';
	var $belongsTo = array(
					 'Url'=>array(
							'className'=>'Url',
							'foreignKey'=>'url_id'));
	function addHit($url)
	{ 	
		$urlData = $this->Url->findByurl($url);
		if(!empty($urlData))
		{	
			$hitData = $this->find('first',array('conditions'=>array('Hit.url_id'=>$urlData['Url']['id'],'date'=>date('Y-m-d')),'order'=>array('date asc')));
				
			if(!empty($hitData))	
			{
				$hitData['Hit']['count'] = $hitData['Hit']['count']+1;
				$this->id = $hitData['Hit']['id'];
				$this->savefield('count',$hitData['Hit']['count']);
				//$this->savefield('date',date('Y-m-d'));	
			}
			else
			{
				$this->data['Hit']['url_id'] = $urlData['Url']['id'];
				$this->data['Hit']['count'] = '1';
				$this->data['Hit']['date'] = date('Y-m-d');
				$this->save($this->data);
			}				
		}
		else
		{
			$this->data['Hit']['url_id'] = $urlData['Url']['id'];
			$this->data['Hit']['count' ]= '1';
			$this->data['Hit']['date'] = date('Y-m-d');
			$this->data['Url']['url'] = $url;
			$this->saveAll($this->data);
			//$this->Url->save($this->data);
		}
	}

	function getLastXDays($days)
	{
		//$condition='Hit.date BETWEEN SUBDATE("'.$currentDate.'",20) AND "'.$currentDate.'"';
		$currentDate = date('Y-m-d');
		$condition = 'Hit.date > SUBDATE("'.$currentDate.'",'.$days.')';
		$data = $this->find('all',array('fields'=>'SUM(count),date','group'=>'date','conditions'=>$condition));
		$stats = Set::combine($data,'{n}.Hit.date','{n}.0.SUM(count)');
		$formattedStats = array();
		for($i= 0 ;$i < $days;$i++ )
		{
			$date = date('Y-m-d',strtotime("-$i days"));
			if(!isset($stats[$date]))
			{
				$formattedStats[$date] = 0;
			}else
			{
				$formattedStats[$date] = $stats[$date];
			}
		}
		return $formattedStats; 
	}
	
	
}
?>